package com.my.socket.nio.v7;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ReadWriteTask implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReadWriteTask.class);

    private Selector selector;

    public ReadWriteTask(Selector selector) throws Exception {
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            while (true) {
                int select = this.selector.selectNow();
                if (select == 0) {
                    continue;
                }
                LOGGER.info("{} events incoming...", select);

                Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();

                    if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        socketChannel.read(byteBuffer);
                        byteBuffer.flip();
                        String message = new String(byteBuffer.array());
                        socketChannel.register(selector, SelectionKey.OP_WRITE, message);
                        LOGGER.info("read: {}", message);
                    } else if (selectionKey.isWritable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        String message = (String) selectionKey.attachment();
                        byteBuffer.put(message.getBytes());
                        byteBuffer.flip();
                        socketChannel.write(byteBuffer);
                        socketChannel.close();
                        LOGGER.info("write: {}", message);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("exception caught, the error is {}", e.getMessage());
        }
    }
}
